package cn.larry.common.utils;

import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.StrUtil;
import cn.larry.common.utils.ip.AddressUtils;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;

/**
 * @version 1.0
 * @Author test
 * @Date 2021-07-15 9:16
 */
public class RequestUtils {

    /**
     * 获取请求IP地址
     *
     * @param request
     * @return
     */
    public static String getIPAddress(HttpServletRequest request) {
        return AddressUtils.getIpAddr(request);
    }

    /**
     * 获取 post 请求的 byte[] 数组
     *
     * @param request
     * @return
     * @throws Exception
     */
    public static byte[] getRequestPostBytes(ServletRequest request)
            throws Exception {
        int contentLength = request.getContentLength();
        if (contentLength < 0) {
            return null;
        }
        byte buffer[] = new byte[contentLength];
        for (int i = 0; i < contentLength; ) {

            int readlen = request.getInputStream().read(buffer, i,
                    contentLength - i);
            if (readlen == -1) {
                break;
            }
            i += readlen;
        }
        return buffer;
    }

    /**
     * 获取 post 请求内容
     *
     * @param request
     * @return
     * @throws Exception
     */
    public static String getRequestPostStr(ServletRequest request) throws Exception {
        byte buffer[] = getRequestPostBytes(request);
        String charEncoding = request.getCharacterEncoding();
        if (charEncoding == null) {
            charEncoding = "UTF-8";
        }
        return new String(buffer, charEncoding);
    }


    /**
     * 获取公网出口地址
     *
     * @return IP地址的字符串形式。出错返回空串。
     */
    public static String getExternalIP() {
        try {
            URL checkIpWebsite = new URL("http://checkip.amazonaws.com");
            String ip;
            try (BufferedReader in = new BufferedReader(new InputStreamReader(checkIpWebsite.openStream()))) {
                ip = in.readLine();
            }
            return ip;
        } catch (IOException e) {
            return "";
        }
    }


    private static String localhostName;

    /**
     * 获取主机名称，一次获取会缓存名称
     *
     * @return 主机名称
     * @since 5.4.4
     */
    public static String getLocalHostName() {
        if (StrUtil.isNotBlank(localhostName)) {
            return localhostName;
        }

        final InetAddress localhost = NetUtil.getLocalhost();
        if (null != localhost) {
            String name = localhost.getHostName();
            if (StrUtil.isEmpty(name)) {
                name = localhost.getHostAddress();
            }
            localhostName = name;
        }

        return localhostName;
    }

}

